package com.xli.sso.security.provider;

import com.xli.sso.security.identity.LoginUser;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;

@Component
public class CustomAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authenticationSupplier, RequestAuthorizationContext context) {
        Authentication authentication = authenticationSupplier.get();
        String requestUrl = context.getRequest().getRequestURI();
        // 获取当前用户的角色
        Collection<String> userRoles = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .toList();

        // 动态加载权限信息，例如从数据库中获取
        Collection<String> requiredRoles = getRequiredRolesForUrl(requestUrl);

        // 检查用户是否具有所需的角色
        return new AuthorizationDecision(userRoles.stream().anyMatch(requiredRoles::contains));
    }

    private Collection<String> getRequiredRolesForUrl(String url) {
        // 这里可以实现从数据库或者其他来源动态加载权限的逻辑
        if ("/admin".equals(url)) {
            return List.of("ROLE_ADMIN");
        }
        else if ("/user".equals(url)) {
            return List.of("ROLE_USER");
        }
        return List.of();
    }
}
